package com.sealer.mybatis;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sealer.mybatis.mapper.UserMapper;
import com.sealer.mybatis.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by sealer on 07-11-2017.
 */
public class Main {
    public static void main(String[] args) throws IOException {
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        //deleteByPrimaryKey
        /*int id = userMapper.deleteByPrimaryKey(3);
        sqlSession.commit();
        System.out.println(id);*/

        //insert
        /*User user = new User();
        user.setBirthday(new Date());
        user.setSex("male");
        user.setUsername("sealer");
        int id = userMapper.insert(user);
        sqlSession.commit();
        System.out.println(user.getId());*/


        //updateByIdSelective
        /*User user = new User();
        user.setBirthday(new Date());
        user.setId(3);
        user.setUsername("azure");
        user.setSex("female");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -1);
        user.setBirthday(cal.getTime());
        userMapper.updateByIdSelective(user);
        sqlSession.commit();*/

        //selectByIdList
        /*List<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        List<User> users = userMapper.selectByIdList(ids);
        for (int i = 0; i < users.size(); i++) {
            System.out.println(users.get(i));
        }*/

        //selectByIdSex
        /*User user = userMapper.selectByIdSex(3, "male");
        System.out.println(user);*/

        //selectUserByIdProc
        /*User user = new User();
        user.setId(3);
        userMapper.selectUserByIdProc(user);
        System.out.println("用户名是： " + user.getUsername());*/

        //selectAll
        PageHelper.startPage(2, 5);
        List<User> list = userMapper.selectAll();

        long total = ((Page)list).getTotal();
        System.out.println(total + "=========");

        for (User user: list) {
            System.out.println(user);
        }
        sqlSession.close();
    }
}
